<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', 0);

$cat = MiscUtils::getParam('cat', 1);
$from = MiscUtils::getParam('from', '');
$to = MiscUtils::getParam('to', '');
if ($cat == 0 && $from == '') {
  $from = date("Y-m-d", strtotime('last monday', strtotime('tomorrow')));
} else if ($cat == 1 && $from == '') {
  $from = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
} else if ($cat == 2 && $from == '') {
  $from = date("Y M", mktime(0, 0, 0, 1, 1, date("Y")));
} else if ($cat == 3 && $from == '') {
  $from = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
} else if ($cat == 4 && $from == '') {
  $from = date("Y M", mktime(0, 0, 0, 1, 1, date("Y")));
} else if ($cat == 5 && $from == '') {
  $from = date("Y", mktime(0, 0, 0, 1, 1, date("Y") - 9));
}

if ($cat == 0 && $to == '') {
  $to = 7;
} else if ($cat == 1 && $to == '') {
  $to = cal_days_in_month(CAL_GREGORIAN, date("m", strtotime($from)), date("Y", strtotime($from)));
} else if ($cat == 2 && $to == '') {
  $to = 12;
} else if ($cat == 3 && $to == '') {
  $to = cal_days_in_month(CAL_GREGORIAN, date("m", strtotime($from)), date("Y", strtotime($from)));
} else if ($cat == 4 && $to == '') {
  $to = 12;
} else if ($cat == 5 && $to == '') {
  $to = 10;
}


$real_from = $from;
if ($cat == 5) {
  $real_from = $from . '-01-01';
}

$title = 'New Customers';
if ($cat == 0) {
  $unit = 'day';
  $title .= ' This Week';
} else if ($cat == 1) {
  $unit = 'day';
  $title .= ' This Month';
} else if ($cat == 2) {
  $unit = 'month';
  $title .= ' This Year';
} else if ($cat == 3) {
  $unit = 'day';
  $max_to = 31;
  $title .= ' from ' . $from . ' to ' . date('Y-m-d', strtotime($real_from . ' + 1 ' . $unit));
} else if ($cat == 4) {
  $unit = 'month';
  $max_to = 12;
  $title .= ' from ' . $from . ' to ' . date('Y M', strtotime($real_from . ' + 1 ' . $unit));
} else if ($cat == 5) {
  $unit = 'year';
  $max_to = 10;
  $title .= ' from ' . $from . ' to ' . date('Y', strtotime($real_from . ' + 1 ' . $unit));
}

//dates
$dates = array();
$date = date('Y-m-d', strtotime($real_from));
for ($i = 0, $il = $to; $i <= $il; $i++) {
  $dates[] = $date;
  $date = date('Y-m-d', strtotime($date . ' + 1 ' . $unit));
}

$data = array();
$max_orders = 0;
$my_total = 0;
for ($i = 0, $il = count($dates) - 1; $i < $il; $i++) {
  $cond_vals = new stdClass();
  $cond_vals->c = 'reg_date >= :v1 AND reg_date < :v2 AND is_actived > 0';
  $cond_vals->v = array(':v1' => $dates[$i], ':v2' => $dates[$i + 1]);
  $opt = new stdClass();
  $opt->select_expr = 'COUNT(t.id) AS _total';
  $total = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, $opt)->d[0]->_total;
  if (!$total) {
    $total = 0;
  }
  $my_total += $total;
  $max_orders = max($total, $max_orders);
  $data[] = array($dates[$i], $total, "$total");
}
$title .= ', Total: ' . $my_total;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
  padding: 0;
  margin: 0;
}
.styled-select {
  width: 240px;
  height: 34px;
  overflow: hidden;
  background: url(images/down_arrow_select.jpg) no-repeat right #ddd;
  border: 1px solid #ccc;
  margin-left: 5px;
}
.styled-select select {
  background: transparent;
  width: 268px;
  padding: 5px;
  font-size: 16px;
  line-height: 1;
  border: 0;
  border-radius: 0;
  height: 34px;
  -webkit-appearance: none;
}
.styled-select option {
  padding: 5px;
  font-size: 16px;
  line-height: 1;
}
.drwrap {
  background: #ddd;
  border: 1px solid #666;
  margin-left: 5px;
  font-family: Lucida Sans Unicode;
}
.drwrap input[type=text] {
  height: 25px;
  padding-left: 5px;
  font-family: Trebuchet MS;
  vertical-align: middle;
}
.drwrap input.start, select {
  border: 1px solid #aaa;
  width: 80px;
}
.drwrap select {
  height: 25px;
  width: 85px;
}
.drwrap td {
  vertical-align: middle;
}
.drwrap td.btn {
  padding: 5px;
  cursor: pointer;
}
.drwrap td.btn:hover {
  background: #ccc;
}
.title {
  font-family: Lucida Sans Unicode;
  font-weight: bold;
  background: #fff;
  border: 1px solid #ddd;
  padding: 5px 10px;
  width: 550px;
  color: DarkRed ;
}
</style>
</head>
<body>
<table cellPadding=0 cellSpacing=0>
  <tr>
    <td>
      <div class="styled-select">
        <select id="s_cat" onchange="reset();">
          <option>This Week</option>
          <option>This Month</option>
          <option>This Year</option>
          <option>View By Days</option>
          <option>View By Months</option>
          <option>View By Years</option>
        </select>
      </div>
    </td>
    <?php if ($cat > 2) { ?>
    <td>
      <div class="drwrap">
        <table cellpadding=0 cellspacing=0>
          <tr>
            <td>&nbsp;Start From&nbsp;</td>
            <td>
              <?php if ($cat != 5) { ?>
              <input id="s_from" type="text" class="start" value="<?php echo $from; ?>" class="date-picker"></input>
              <?php } else { ?>
              <select id="s_from" ></select>
              <?php } ?>
            </td>
            <td>&nbsp;show&nbsp;</td>
            <td><input id="s_to" type="text" style="width: 40px;height: 20px;" value="<?php echo $to; ?>"></input></td>
            <td>&nbsp;<?php echo $unit; ?>s&nbsp;</td>
            <td class="btn"><img src="images/find.png" onclick="search();"></img></td>
          </tr>
        </table>
      </div>
    </td>
    <?php } ?>
  </tr>
</table>
<div>&nbsp;</div>
<div class="title"><?php echo $title; ?></div>
<div id="chart1" style="height:400px; width:1280px;"></div>
<div>&nbsp;</div>
<div>&nbsp;</div>
<script src="../../../libs/jquery/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script src="../../../libs/jquery_ui/js/jquery-ui-1.10.2.custom.js"></script>
<link href="jquery_ui/css/smoothness/jquery-ui-1.10.2.custom.css" rel="stylesheet">
<script type="text/javascript" src="../../../libs/jqplot/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="../../../libs/jqplot/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="../../../libs/jqplot/plugins/jqplot.dateAxisRenderer.min.js"></script>
<link rel="stylesheet" type="text/css" hrf="../../../libs/jqplot/jquery.jqplot.min.css" />
<script type="text/javascript" src="../../../libs/jqplot/plugins/jqplot.pointLabels.min.js"></script>
<script src="js/jquery.mtz.monthpicker.js"></script>
<script type="text/javascript">
var _data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');

function reset() {
  parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id"; ?>&cat=' + $('#s_cat')[0].selectedIndex;
}

function search() {
  var from = '';
  <?php if ($cat == 5) { ?>
  from = $('#s_from')[0].options[$('#s_from')[0].selectedIndex].value;
  parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id"; ?>&cat=' + $('#s_cat')[0].selectedIndex + '&from=' + from + '&to=' + $('#s_to')[0].value;
  <?php } else if ($cat > 2) { ?>
  from = $('#s_from')[0].value;
  parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id"; ?>&cat=' + $('#s_cat')[0].selectedIndex + '&from=' + from + '&to=' + $('#s_to')[0].value;
  <?php } ?>
}

$(function(){
  $('#s_cat')[0].selectedIndex = <?php echo $cat; ?>;
  <?php if ($cat > 2) { ?>
    var MIN = 1;
    var MAX = <?php echo $max_to; ?>;
    $('#s_to').spinner({ min: MIN, max: MAX });
    $('#s_to').on('keyup', function(e) {
      var v = parseInt($(this).val());
      if (isNaN(v)) {
        return $(this).val(MIN);
      }
      if ($(this).val() < MIN) {
        $(this).val(MIN);
      } else if ($(this).val() > MAX) {
        $(this).val(MAX);
      } else {
        $(this).val(v);
      }
    });
    <?php if ($cat == 3) { ?>
    $('#s_from').datepicker( {
      changeMonth: true,
      changeYear: true,
      showButtonPanel: true,
      dateFormat: 'yy-mm-dd',
      onSelect: function(dateText) {
        var d = new Date(dateText);
        if (d.getDate() == 1) {
          $('#s_to')[0].value = MyUtils.daysInMonth(d.getMonth() + 1, d.getFullYear());
        }
        search();
      }
    });
    <?php } else if ($cat == 4) { ?>
    $('#s_from').monthpicker({
      pattern: 'yyyy mmm' // Default is 'mm/yyyy' and separator char is not mandatory
    });
    $('#s_from').monthpicker().bind('monthpicker-click-month', function (e, month) {
      search();
    });
    <?php } else if ($cat == 5) { ?>
    for (i = new Date().getFullYear(); i > 1900; i--) {
      $('#s_from').append($('<option />').val(i).html(i));
      if (i == '<?php echo $from; ?>') {
        $('#s_from')[0].selectedIndex = $('#s_from')[0].options.length - 1;
      }
    }
    $('#s_from')[0].onchange = function() {
      search();
    };
    <?php } ?>
  <?php } ?>
  var plot1 = $.jqplot('chart1', [_data], {
    seriesDefaults: {
      rendererOptions: {
        smooth: true
      },
      showMarker:false,
      pointLabels: { show:true } 
    },
    axes:{
      xaxis:{
        renderer:$.jqplot.DateAxisRenderer,
        <?php if ($cat == 0) { ?>
        tickOptions:{formatString:'%a (%#m-%#d)'},
        <?php } else if ($cat == 1 || $cat == 3) { ?>
        tickOptions:{formatString:'%#m-%#d'},
        <?php } else if ($cat == 2 || $cat == 4) { ?>
        tickOptions:{formatString:'%Y %b'},
        <?php } else if ($cat == 5) { ?>
        tickOptions:{formatString:'%Y'},
        <?php } ?>
        tickInterval:'1 <?php echo $unit; ?>'
      },
      yaxis: {
        min: 0,
        max: <?php echo $max_orders * 1.5; ?>,
        tickOptions: {
          prefix: '$',
          showLabel: false
        }
      }
    }
  });
});
</script>
</body>
</html>